package com.foucus.myfouces.MVP.View.views.Fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.foucus.myfouces.Adapter.SkillAdapter;
import com.foucus.myfouces.Api.GankService;
import com.foucus.myfouces.Base.BaseFragment;
import com.foucus.myfouces.Base.BaseReq;
import com.foucus.myfouces.Base.Setting;
import com.foucus.myfouces.MVP.Model.DirectorActicleResp;
import com.foucus.myfouces.MVP.Model.BannerResp;
import com.foucus.myfouces.R;
import com.foucus.myfouces.Resource.HttpUtil.ServiceFactory;
import com.foucus.myfouces.Resource.Util.GsonImpl;
import com.foucus.myfouces.Resource.Util.JsonUtil;
import com.foucus.myfouces.Resource.Util.SharedPreferencesUtil;
import com.foucus.myfouces.Resource.Util.StartActivity;
import com.foucus.myfouces.Resource.view.MyRecyclerView;
import com.foucus.myfouces.Resource.view.OnRcvScrollListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yf-06 on 2017/6/27.
 * 技巧
 */

public class SkillFg extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.img_back)
    ImageView img_back;
    @Bind(R.id.lly_back)
    LinearLayout lly_back;
    @Bind(R.id.tv_title_bar_title)
    TextView tv_title_bar_title;
    @Bind(R.id.img_title_bar_right)
    ImageView img_title_bar_right;
    @Bind(R.id.lly_title_bar_right)
    LinearLayout lly_title_bar_right;
    @Bind(R.id.tv_save)
    TextView tv_save;
    @Bind(R.id.rcv_skill_fg)
    MyRecyclerView rcv_skill_fg;
    @Bind(R.id.rxtext_skill_fg)
    PtrClassicFrameLayout rxtext_skill_fg;
    private View rootView;
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private List<BannerResp.ResultBean.DataBean> bannerList;
    private List<DirectorActicleResp.ResultBean.DataBean> directorList;
    private View heardview, footerview; //recycler添加头部和底部
    private SkillAdapter setAdapter;
    boolean isLoading; //判断是否还有数据可以加载
    private boolean isFooterview = true; //判断是否到底部

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_skill, container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = getActivity();
        init();
        initRecycleview();
        getBannerAd();
    }

    private void init() {
        tv_title_bar_title.setText("技巧");
        bannerList = new ArrayList<>();
        directorList = new ArrayList<>();
        rxtext_skill_fg.autoRefresh();
        rxtext_skill_fg.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getBannerAd();
            }
        });
    }

    private void initRecycleview() {

        rcv_skill_fg.setLayoutManager(new GridLayoutManager(mActivity, 1));
        // RecyclerView底部加载view
        footerview = LayoutInflater.from(mActivity).inflate(R.layout.footerview, null);

        // RecyclerView头部view
        heardview = LayoutInflater.from(mActivity).inflate(R.layout.heardview_skill, null);


        /**
         *  监听recyclerView是否到底部
         */
        rcv_skill_fg.addOnScrollListener(new OnRcvScrollListener(rcv_skill_fg) {
            @Override
            public void onBottom() {
                super.onBottom();
                if (!isLoading) {
                    isLoading = true;
                    getDirectorActicle(MORE);
                    Log.e("ssss", "到达底部");
                }
            }

            @Override
            public void onScrollldistance(int distance, int position) {
                super.onScrollldistance(distance, position);
                if (position == 0) {
//                    if (distance > 300) {
//                        floatingActionButton.setVisibility(View.VISIBLE);
//                    } else {
//                        floatingActionButton.setVisibility(View.GONE);
//                    }
                }
            }
        });
    }

    private void initBanner() {


    }

    /**
     * 获取广告栏数据
     */
    private void getBannerAd() {
        BaseReq req = new BaseReq();
        req.setValue("type", "3");
        ServiceFactory.getInstance()
                .createService(GankService.class)
                .getBannerAd(req.getSecret("获取技巧广告栏"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {
                        initBanner();
                        getDirectorActicle(REFRESH);
                    }

                    @Override
                    public void onError(Throwable e) {
                        rxtext_skill_fg.refreshComplete();
                    }

                    @Override
                    public void onNext(ResponseBody argumentResp) {

                        String response = JsonUtil.JsonToStr(argumentResp);
                        boolean isflag = Setting.isRight(mActivity, response);
                        if (isflag) {
                            BannerResp resp = GsonImpl.get().toObject(response, BannerResp.class);
                            bannerList.clear();
                            bannerList.addAll(resp.getResult().getData());
                        } else {
                        }
                    }
                });
    }

    /**
     * 获取文章
     */
    private void getDirectorActicle(final int type) {
        if (type == REFRESH || type == LOAD) {
            page = 1;
        } else {
            page = (directorList.size() / 20 + 1);
        }
        BaseReq req = new BaseReq();
        req.setValue("member", "null");
        req.setValue("category", "0");
        req.setValue("page", page + "");
        req.setValue("page_size", "20");
        req.setValue("order", "id");
        req.setValue("sort", "desc");
        ServiceFactory.getInstance()
                .createService(GankService.class)
                .getPost(req.getSecret("获取技巧页面文章"))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {
                        rxtext_skill_fg.refreshComplete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        rxtext_skill_fg.refreshComplete();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        String response = JsonUtil.JsonToStr(responseBody);
                        boolean isflag = Setting.isRight(mActivity, response);
                        if (isflag) {
                            DirectorActicleResp resp = GsonImpl.get().toObject(response.toString(), DirectorActicleResp.class);
                            int total = resp.getResult().getMeta().getPagination().getTotal();
                            Log.e("ssss", "total==>" + total);

                            if (type == REFRESH || type == LOAD) {
                                directorList.clear();
                                directorList.addAll(resp.getResult().getData());
                            } else {
                                directorList.addAll(resp.getResult().getData());
                            }
                            Log.e("ssss", "directorList.size()==>" + directorList.size());
                            if (directorList.size() < total) {
                                isLoading = false;
                            }
                            setAdapter1(total);

                        }
                    }
                });
    }

    @OnClick({R.id.lly_title_bar_right})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lly_title_bar_right:
                Log.e("ssss", "搜索");
                break;
        }
    }

    private void setAdapter1(int total) {

        if (setAdapter == null) {

            setAdapter = new SkillAdapter(directorList, mActivity, total);
            rcv_skill_fg.setAdapter(setAdapter);
            setAdapter.addHeaderView(heardview);
            setAdapter.addFooterView(footerview);
            setAdapter.notifyDataSetChanged();

        } else {
            if (!isFooterview) {
                Log.e("ssss", "添加底部view");
                setAdapter.addFooterView(footerview);
                setAdapter.notifyDataSetChanged();
            }
            //当底部没数据时 将添加到底部的view删除
            if (directorList.size() >= total) {
                Log.e("ssss", "删除底部view");
                setAdapter.deleteFoolterView();
                setAdapter.notifyDataSetChanged();
            } else {
                setAdapter.notifyDataSetChanged();
            }
        }
        isFooterview = setAdapter.haveFooterView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


}
